<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="600"></canvas>
    <script>
      //预加载: 先把资源加载号 然后再使用

      //一.一张图片的预加载
      //canvas:画布可以把图片画到画布上 前提 图片需要加载好
      // var canvas = document.querySelector("#myCanvas")
      // var context = canvas.getContext("2d")
      // //加载一个图片
      // var img = document.createElement("img")
      // ;(img.src =
      //   "https://img0.baidu.com/it/u=2028084904,3939052004&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"),
      //   console.log(img)
      // //图片加载好的事件
      // img.onload = function () {
      //   console.log("图片加载完毕了")
      //   //再把图片绘制到canvas画布上
      //   context.drawImage(img, 0, 0, 200, 200)
      // }

      //console.log("执行了")

      //二.多张图片的预加载
      var canvas = document.querySelector("#myCanvas");
      var context = canvas.getContext("2d");
      var imgs = [
        "https://img0.baidu.com/it/u=2028084904,3939052004&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
        "https://img1.baidu.com/it/u=3573056321,2239143646&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
        "https://img2.baidu.com/it/u=617579813,2960860841&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800",
      ];
      function loadImg(imgs, cb) {
        var num = 0;
        //返回一个 所有图片加载完毕之后的时刻
        var imgArr = [];
        imgs.forEach(function (img) {
          var myimg = document.createElement("img");
          myimg.src = img;

          myimg.onload = function () {
            console.log("加载完毕了");
            num++;
            imgArr.push(this);
            //console.log("num")
            if (num == imgs.length) {
              console.log("三张都加载完毕了");
              cb && cb(imgArr); //回调函数可以传可以不传
            }
          };
        });
      }
      loadImg(imgs, function (imgArr) {
        console.log(imgArr);
        context.drawImage(imgArr[0], 0, 0, 100, 100);
        context.drawImage(imgArr[1], 100, 100, 100, 100);
        context.drawImage(imgArr[2], 200, 200, 100, 100);
      });
    </script>
  </body>
</html>
